<?php

namespace App\Admin\Controllers\Blacklist;

use App\Http\Controllers\Controller;
use App\Model\Blacklist\BlacklistStrategy;
use App\Util\InfoUtil;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Form;
use Encore\Admin\Form\Tools;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;
use App\Model\Blacklist\BlacklistSetting;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\MessageBag;

class BlacklistSettingController extends Controller
{
    use ModelForm;

    public function index()
    {
        $content = new Content();
        $content->header('黑名单设置');
        $content->body($this->grid());
        return $content;
    }

    public function edit($id)
    {
        $content = new Content();
        $content->header('黑名单管理');
        $content->body($this->form('edit', $id)->edit($id));
        return $content;
    }

    public function create()
    {
        $content = new Content();
        $content->header('黑名单管理');
        $content->body($this->form());
        return $content;
    }

    protected function grid()
    {
        $grid = new Grid(new BlacklistSetting());
        $grid->model()->orderBy('id', 'desc');
        $grid->id('记录id');
        $grid->column("strategy.name", "策略");
        $grid->val('值');
        // 不存在的`full_name`字段
        $grid->column('full_name', "创建时间")->display(function () {
            return $this->updated_at->format('Y-m-d H:i:s');
        });
        $grid->disableExport();
        $grid->disableRowSelector();
        $grid->filter(function ($filter) {
            $filter->column(1/2, function ($filter) {
                $filter->equal('strategy_id',"策略")->select(BlacklistStrategy::all()->pluck('name','id'));
            });
            $filter->column(1/2, function ($filter) {
                $filter->like('val', '值');
            });
            //$filter->expand();
            $filter->disableIdFilter();
        });

        $grid->actions(function (Actions $actions) {
            //$actions->disableDelete();
            $actions->disableView();
            // $actions->disableEdit();

        });
        return $grid;
    }

    protected function form($mode = '', $id = '')
    {
        $form = new Form(new BlacklistSetting());
        $form->select('strategy_id', "黑名单策略")->options(BlacklistStrategy::all()->pluck('name', 'id'));
        if ($form->isEditing()) {
            $form->text('val', "具体值")
                ->creationRules('unique:blacklist_setting,val')
                ->updateRules('unique:blacklist_setting,val,{{id}}');
        } else {
            $form->list('values', "具体值")->required();
        }
        $form->saving(function (Form $form) {
            if ($form->isEditing()) {
                $m = $form->model();
                $m->val = $form->val;
                $m->strategy_id = $form->strategy_id;
                $m->updated_at = date('Y-m-d H:i:s');
                $res = $m->save();
                if ($res) {
                    $this->updateBlacklistCache();
                    $success = new MessageBag([
                        'title' => '修改',
                        'message' => '操作成功',
                    ]);
                    return redirect('/blacklist_setting')->with(compact('success'));
                }
            }
            $res = $this->batchSave($form);
            if ($res) {
                $this->updateBlacklistCache();
                $success = new MessageBag([
                    'title' => '创建',
                    'message' => '操作成功',
                ]);
                return redirect('/blacklist_setting')->with(compact('success'));
            }

            return InfoUtil::adminErr("保持失败！");
        });

        $form->tools(function (Tools $tools) {
            //$tools->disableList();
            $tools->disableDelete();
            $tools->disableView();
        });
        return $form;
    }

    /**
     * 维护黑名单缓存
     */
    private function updateBlacklistCache()
    {
        $list = BlacklistSetting::get(['strategy_id', 'val']);
        $data = [];
        if ($list) {
            foreach ($list as $v) {
                $k = "strategyId:" . $v->strategy_id;
                $data[$k][] = $v->val;
            }
        }
        Redis::set("blacklist", serialize($data));
        return true;
    }

    /**
     * 批量保持
     * @param Form $form
     * @return bool
     */
    private function batchSave(Form $form)
    {
        $values = $form->values;
        $strategy_id = $form->strategy_id;
        $v = $values['values'];
        $t = date('Y-m-d H:i:s');
        if ($v) {
            $len = count($values['values']);
            $sql = 'insert ignore into t_blacklist_setting (`strategy_id`,`val`,`updated_at`,`created_at`) values ';
            for ($i = 0; $i < $len; $i++) {
                if ($v[$i]) {
                    $item = ' ( ' . $strategy_id . ',"' . trim($v[$i]) . '","' . $t . '","' . $t . '"),';
                    $sql .= $item;
                }
            }
            $sql = substr($sql, 0, -1);
            return DB::insert($sql);
        }
        return false;
    }
}

